package com.app.lxx.pregnancyberth.Mvp.Presenter;

import android.util.Log;

import com.app.lxx.pregnancyberth.Mvp.Model.CurrencyModel;
import com.app.lxx.pregnancyberth.Mvp.View.CurrencyView;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * Created by Lxx on 2018/9/13.
 */

public class CurrencyPresenter extends BasePresenter<CurrencyView, CurrencyModel> {

    public void requestPost(final int type, String url) {
        getmodle().requestPostHttpModel(url, stringCallback(type));
    }

    public void requestPost(int type, String url, HashMap<String, String> hashMap) {
        getmodle().requestPostHttpModel(url, hashMap, stringCallback(type));
    }

    public void requestGet(int type, String url) {
        getmodle().requestGetHttpModel(url, stringCallback(type));
    }

    public void requestGet(int type, String url, HashMap<String, String> hashMap) {
        getmodle().requestGetHttpModel(url, hashMap, stringCallback(type));
    }

    private StringCallback stringCallback(final int type) {
        return new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
//                String body = response.body();
//                getV().requestCurrencyView(type, body);
//
                try {
                    String body = response.body();
                    JSONObject jsonObject = new JSONObject(body);
                    if (body.contains("code")) {
                        int code = jsonObject.getInt("code");
                        if (code == 1 || code == 3) {
                            getV().requestCurrencyView(type, body);
                        } else {
                            getV().showToast(jsonObject.getString("msg"));
                            getV().requestCurrencyViewFailed(type, response.code());
                        }
                    } else {
                        getV().requestCurrencyView(type, body);
                    }

                    Log.e("OkGo", "type==>" + type + "\n" + body);
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    Log.e("OkGo", "type==>" + type + "\n" + e.getMessage());
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                String localizedMessage = response.getException().getLocalizedMessage();
                Log.e("OkGo", "type==>" + type + "\n" + localizedMessage);
                getV().requestCurrencyViewFailed(type, response.code());
            }
        };
    }
}
